package com.thinkgem.jeesite.common.listener.order;

import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.thinkgem.jeesite.modules.product.entity.product.GenProduct;
import com.thinkgem.jeesite.modules.product.service.product.GenProductService;
import com.thinkgem.jeesite.modules.shop.constant.order.ShopOrderConstant;
import com.thinkgem.jeesite.modules.shop.entity.info.ShopOrderInfo;
import com.thinkgem.jeesite.modules.shop.entity.order.ShopOrder;
import com.thinkgem.jeesite.modules.shop.service.order.ShopOrderService;

/**
 * 删除服务器上的文件
 * 
 * @author xiaoqun.yi
 */
// 实现Runnable接口(推荐)，可以线程接口，预留一个extends(继承)，方便扩展
public class OrderManager implements Runnable {

	public ServletContextEvent sce;
	ShopOrderService shopOrderService;
	GenProductService genProductService;
    /**
     * 构造函数。初始化参数 @param path
     */
    public OrderManager(ServletContextEvent sce) {
    	this.sce = sce;
    }

    /**
     * 把线程要执行的代码放在run()中
     */
    public void run() {
        System.out.println("管理开始=========");
        
        if (shopOrderService == null) {
        	ServletContext sc = sce.getServletContext();
        	WebApplicationContext beans = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
        	shopOrderService = (ShopOrderService) beans.getBean("shopOrderService");
        }
        
        if (genProductService == null) {
        	ServletContext sc = sce.getServletContext();
        	WebApplicationContext beans = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
        	genProductService = (GenProductService) beans.getBean("genProductService");
        }
        
        List<ShopOrder> orders = shopOrderService.findNewList();
        for (ShopOrder order : orders) {
        	 long second = (order.getCreateTime().getTime() + 30 * 60 * 1000 - new Date().getTime()) / 1000;
        	 System.out.println(second);
        	 if (second <= 0) {
        		 List<ShopOrderInfo> infos = order.getShopOrderInfoList();
        		 for (ShopOrderInfo info : infos) {
        			 GenProduct product = new GenProduct();
        			 product.setId(info.getProductId());
        			 product = genProductService.get(product);
        			 product.setStock(String.valueOf(Long.parseLong(product.getStock()) + info.getCount()));
        			 genProductService.updateStock(product);
        		 }
        		 order.setStatus(ShopOrderConstant.ORDER_CANCEL);
        		 shopOrderService.cancelOrder(order);
             }
        }
        System.out.println("遍历结束=========");
    }
}
